package com.fsm.common.easyexcel.util;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.fsm.common.easyexcel.config.EasyExcelTitleHandler;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class EasyExcelUtil<T> {
    /**
     * 导出excel
     * @param outputStream 输出流
     * @param dataList     导出的数据
     * @param classT        模板类
     * @param sheetName     sheetName
     * @param writeHandlers    样式处理类
     */
    public void writeExcelWithModel(OutputStream outputStream, List<T> dataList, Class<?> classT, String sheetName, WriteHandler... writeHandlers) {

        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
//        // 标题字体大小
//        WriteFont contentWriteFont = new WriteFont();
//        contentWriteFont.setFontHeightInPoints((short) 12);
//        headWriteCellStyle.setWriteFont(contentWriteFont);
//        //标题黄色底纹
//        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        // 单元格策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//        //边框
//        contentWriteCellStyle.setBorderBottom(BorderStyle.THIN);
//        contentWriteCellStyle.setBorderLeft(BorderStyle.THIN);
//        contentWriteCellStyle.setBorderRight(BorderStyle.THIN);
//        contentWriteCellStyle.setBorderTop(BorderStyle.THIN);
//        // 设置自动换行，前提内容中需要加「\n」才有效
//        contentWriteCellStyle.setWrapped(true);
        // 初始化表格样式
        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        ExcelWriterSheetBuilder excelWriterSheetBuilder = EasyExcel.write(outputStream, classT).sheet(sheetName).registerWriteHandler(horizontalCellStyleStrategy);
        if (null != writeHandlers && writeHandlers.length > 0) {
            for (WriteHandler writeHandler : writeHandlers) {
                excelWriterSheetBuilder.registerWriteHandler(writeHandler);
            }
        }
        // 开始导出
        excelWriterSheetBuilder.doWrite(dataList);
    }

    public static void setResponseHeader(HttpServletResponse response, String fileName) {

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String excelName = "";
        try {
            excelName = URLEncoder.encode(fileName, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.addHeader("Access-Control-Expose-Headers", "*");
        response.setHeader("Content-disposition", "attachment;filename=" + excelName + ".xlsx");
    }

    /**
     * 在读取Excel表格数据时, 将读取的每行记录映射成List<List<String>>记录, 而没有映射成实体类
     * @param fis
     * @return
     * @throws Exception
     */
    public static List<List<String>> parseFromExcel(InputStream fis) throws Exception{
        List<List<String>> result = new ArrayList<>();
        Workbook workbook = WorkbookFactory.create(fis);
        int sheetNumber =  workbook.getNumberOfSheets();
        short cellNumber = workbook.getSheetAt(0).getRow(0).getLastCellNum();
        for(int sheetNo = 0;sheetNo < sheetNumber; sheetNo++){
            Sheet sheet = workbook.getSheetAt(sheetNo);
            int lastRaw = sheet.getLastRowNum();
            for (int rawNo = 1; rawNo <= lastRaw; rawNo++) {
                List<String> rowArray = new ArrayList<>();
                //第rawNo行
                Row row = sheet.getRow(rawNo);
                for(short cellNo = 0;cellNo < cellNumber;cellNo++){
                    Cell cell = row.getCell(cellNo);
                    if(cell == null){
                        rowArray.add("");
                    }else{
                        cell.setCellType(CellType.STRING);
                        rowArray.add(cell.getStringCellValue());
                    }
                }
                result.add(rowArray);
            }
        }
        return result;
    }

}
